// 搜索图片像素序列
function searchImage(image1) {
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        sw = image1.width,  // 原图宽度                
        sh = image1.height,  // 原图高度                
        tw = 8,  // 模板宽度                
        th = 8;  // 模板高度
    canvas.width = tw;
    canvas.height = th;
    ctx.drawImage(image1, 0, 0, sw, sh, 0, 0, tw, th);
    var pixels = ctx.getImageData(0, 0, tw, th);
    return toGrayBinary(pixels, true, null, true);
}

// 像素数据，是否二值化（bool），二值化闵值（0-255），是否返回二值化后序列（bool）        
function toGrayBinary(pixels, binary, value, sn) {
    var r, g, b, g, avg = 0, len = pixels.data.length, s = '';
    for (var i = 0; i < len; i += 4) {
        avg += (.299 * pixels.data[i] + .587 * pixels.data[i + 1] + .114 * pixels.data[i + 2]);
    }
    avg /= (len / 4);
    for (var i = 0; i < len; i += 4) {
        r = .299 * pixels.data[i],
            g = .587 * pixels.data[i + 1],
            b = .114 * pixels.data[i + 2];
        if (binary) {
            if ((r + g + b) >= (value || avg)) {
                g = 255;
                if (sn) s += '1';
            } else {
                g = 0;
                if (sn) s += '0';
            }
            g = (r + g + b) > (value || avg) ? 255 : 0;
        } else {
            g = r + g + b;
        }
        pixels.data[i] = g,
            pixels.data[i + 1] = g,
            pixels.data[i + 2] = g;
    }
    if (sn) return s;
    else return pixels;
}